package com.zhuizikejithreeig.cn.threeigkeji;


import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.ViewDragHelper;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.flyco.tablayout.SlidingTabLayout;
import com.zhuizikejithreeig.cn.been.HaveSetBeen;
import com.zhuizikejithreeig.cn.been.NewMainBeen;
import com.zhuizikejithreeig.cn.been.RegistStataBeen;
import com.zhuizikejithreeig.cn.been.UpDataBeen;
import com.zhuizikejithreeig.cn.contect.ContectUtils;
import com.zhuizikejithreeig.cn.contect.UriContect;
import com.zhuizikejithreeig.cn.threeigkeji.loginfo.BasicInfoActivity;
import com.zhuizikejithreeig.cn.threeigkeji.loginfo.ChioceSetActivity;
import com.zhuizikejithreeig.cn.threeigkeji.loginfo.ChoceOtherActivity;
import com.zhuizikejithreeig.cn.threeigkeji.loginfo.LoginActivity;
import com.zhuizikejithreeig.cn.threeigkeji.loginfo.SettingActivity;
import com.zhuizikejithreeig.cn.threeigkeji.mianinfo.EmailActivity;
import com.zhuizikejithreeig.cn.threeigkeji.mianinfo.EquipFixActivity;
import com.zhuizikejithreeig.cn.threeigkeji.mianinfo.WalletActivity;
import com.zhuizikejithreeig.cn.utils.GsonUtil;
import com.zhuizikejithreeig.cn.utils.ToastMake;
import com.zhuizikejithreeig.cn.utils.Utils;
import com.zhuizikejithreeig.cn.weigit.NoScrollViewPager;
import com.zhuizikejithreeig.cn.fragment.SimpleCardFragment;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.onekeyshare.OnekeyShare;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import okhttp3.Call;
import okhttp3.MediaType;

public class MainActivity extends BasicActivity implements View.OnClickListener {

    private DrawerLayout      mDrawer;
    private LinearLayout      mMoney;
    private LinearLayout      mCustomer;
    private LinearLayout      mSetting;
    private LinearLayout      mFix;
    private SlidingTabLayout  mTabLayout;
    private NoScrollViewPager mViewPager;
    private TextView          mShare;
    private              boolean hasPermission = false;
    private              int     vs_name1      = 0;
    private              int     vs_name2      = 0;
    private              int     vs_name3      = 0;
    private              int     sv_name1      = 0;
    private              int     sv_name2      = 0;
    private              int     sv_name3      = 0;
    private static final int     READSDK       = 200;
    private              int     myProgress    = 0;
    private              long    exitTime      = 0;
    private NewMainBeen mBeen;
    private int         mSize;

    private final String[]            title      = {"主驾", "副驾", "后排左", "后排右"};
    private       ArrayList<Fragment> mFragments = new ArrayList<>();
    private MyPagerAdapter mAdapter;
    private String         mUserId;
    private List<Integer> postion = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_main);
        showBody();
        showBody();
        findViewById(R.id.user).setOnClickListener(this);
        findViewById(R.id.message).setOnClickListener(this);

        mTabLayout = (SlidingTabLayout) findViewById(R.id.slidingtablayout);
        mViewPager = (NoScrollViewPager) findViewById(R.id.viewpager);
        mShare = (TextView) findViewById(R.id.share);
        mDrawer = (DrawerLayout) findViewById(R.id.drawer);

        //侧滑菜单
        mMoney = (LinearLayout) findViewById(R.id.money);
        mCustomer = (LinearLayout) findViewById(R.id.customer);
        mSetting = (LinearLayout) findViewById(R.id.setting);
        mFix = (LinearLayout) findViewById(R.id.fix);

        mMoney.setOnClickListener(this);
        mCustomer.setOnClickListener(this);
        mSetting.setOnClickListener(this);
        mFix.setOnClickListener(this);
        mShare.setOnClickListener(this);

        //TODO:解决全屏滑动而不能出现侧滑
        //        setDrawerLeftEdgeSize(MainActivity.this, mDrawer, 1);

        hasReadPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        //有无网状态
        if (isConnected()) {
            UpdataApk();
        } else {

            //TODO:原则上应该打开Login界面
        }

        mUserId = Utils.getString(ContectUtils.IDSAVE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        chice();
    }

    private void chice() {

        String phone = Utils.getString(ContectUtils.PHONESAVE);
        if (TextUtils.isEmpty(phone) || !Utils.isMobileMian(phone)) {
            mFragments.clear();
            for (int i = 0; i < title.length; i++) {
                if (i == 0) {
                    mFragments.add(SimpleCardFragment.getInstance(i + "", title[i], title[i]));
                } else {
                    mFragments.add(SimpleCardFragment.getInstance(i + 1 + "", title[i], title[i]));
                }
            }
            //一句代码就可以控制是否滑动
            mViewPager.setNoScroll(true);
            mAdapter = new MyPagerAdapter(getSupportFragmentManager());
            mViewPager.setAdapter(mAdapter);
            mTabLayout.setViewPager(mViewPager, title);
            //TODO:原则上要跳到登录界面
            if (!CompontApplayCation.mianToLogin) {

                //为了防止回退的时候
                CompontApplayCation.mianToLogin = true;
                skipOtherActivity(LoginActivity.class, false);

            }
            return;
        } else {
            newHaveRegistData(phone);
        }


    }

    private void newHaveRegistData(String phone) {
        showProgrees("加载中请稍等....");
        OkHttpUtils
                .post()
                .url(UriContect.STATUS)
                .addParams("phone", phone)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        hideProgree();

                        //原则上进入登录界面
//                        Utils.runOnUIThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                skipOtherActivity(LoginActivity.class, true);
//                            }
//                        });

                        return;
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        hideProgree();
                        mBeen = GsonUtil.parseJsonToBean(response, NewMainBeen.class);

                        if (mBeen == null) {
                            //TODO:只要出现错误原则上在登录一次
                            skipOtherActivity(LoginActivity.class, true);
                            return;
                        }
                        if (!TextUtils.equals(mBeen.getStatus(), "200")) {
                            ToastMake.showToast(mBeen.getMsg());
                            //TODO:只要出现错误原则上在登录一次
                            // skipOtherActivity(LoginActivity.class,true);
                            return;
                        } else {
                            //                            //首先记录整个appkey
                            //                            CompontApplayCation.phone = mBeen.getPhone();

                            //TODO:这里的position应该是个集合,并且还要增加一个字段,
                            String type = mBeen.getData();
                            //                            如果状态是1表示尚未完成车辆信息
                            if (TextUtils.equals("1", type)) {
                                //如果注册了没有了注册汽车
                                startActivity(new Intent(MainActivity.this, BasicInfoActivity.class));
                            } else if (TextUtils.equals("2", type)) {
                                //如果车辆状态是2，表示尚未扫码
                                //TODO:如果没有扫描完。进入扫描界面
                                startActivity(new Intent(MainActivity.this, ChioceSetActivity.class));
                            } else if (TextUtils.equals("3", type)) {
                                //表示全部完成

                            } else {
                                //如果有其他的，表示再加入扫码座椅
                                startActivity(new Intent(MainActivity.this, ChoceOtherActivity.class));
                            }

                            //TODO:获取二维码图片
                            if (TextUtils.isEmpty(mUserId)) {
                                skipOtherActivity(LoginActivity.class, true);
                            } else {
                                //TODO:获取已经绑定的座椅
                                if (isConnected()) {
                                    haveCodeImage();
                                } else {
                                    ToastMake.showToast(getResources().getString(R.string.string57));
                                }

                            }


                            //                            //显示消息个数
                            //                            String state = mBeen.getState();
                            //                            if (TextUtils.equals(state, "1")) {
                            //                                setRightShow(1, R.mipmap.message);
                            //                            } else {
                            //                                setRightShow(1, R.mipmap.message_red);
                            //                            }
                            //                            //显示加载照片
                            //                            //设置viewPager关联,并且解决索引越界的问题
                            //                            if (mBeen.getData() != null) {
                            //                                mSize = mBeen.getData().size();
                            //                            } else {
                            //                                mSize = 0;
                            //                            }


                        }

                    }
                });
    }

    private void haveCodeImage() {
        OkHttpUtils
                .post()
                .url(UriContect.GETUSERBINDS)
                .addParams("id", mUserId)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                        ToastMake.showToast(getResources().getString(R.string.string90));
                        hideProgree();

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        hideProgree();
                        mFragments.clear();
                        HaveSetBeen been = GsonUtil.parseJsonToBean(response, HaveSetBeen.class);
                        List<HaveSetBeen.DataBean> mSize = been.getData();
                        //TODO:有二维码图片的集合
                        postion.clear();
                        List<String> uri = new ArrayList<>();
                        for (int i = 0; i < mSize.size(); i++) {
                            postion.add(Integer.parseInt(mSize.get(i).getPosition()));
                            System.out.println("postion"+mSize.get(i).getPosition());
                            uri.add(mSize.get(i).getQrcode());
                        }

                        for (int i = 0; i < title.length; i++) {
                            for (int j = 0; j < postion.size(); j++) {

                                //TODO:座椅的位置是从1开始算起的,而不是哦从零开始的
                                if (i+1 == postion.get(j)) {
                                    mFragments.add(SimpleCardFragment.getInstance((i)+"", uri.get(j), ""));
                                }
                            }
                            //TODO:只有是零的时候进行特殊计算
                            if (i == 0) {
                                mFragments.add(SimpleCardFragment.getInstance("0", title[i], title[i]));
                            }

                            //TODO:为了防止重复不断的加入,要做限制
                            if (mFragments.size() <= i) {
                                mFragments.add(SimpleCardFragment.getInstance((i)+"", "", ""));
                            }
                        }

                        Utils.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                mViewPager.setNoScroll(true);
                                mAdapter = new MyPagerAdapter(getSupportFragmentManager());
                                mViewPager.setAdapter(mAdapter);
                                mTabLayout.setViewPager(mViewPager, title);
                            }
                        });
                    }
                });

    }


    private void hasReadPermission(String permission) {
        PermissionGen.with(MainActivity.this)
                .addRequestCode(READSDK)
                .permissions(
                        permission
                )
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = READSDK)
    public void requestPhotoSuccess() {
        //成功之后的处理
        //.......
        hasPermission = true;
    }

    @PermissionFail(requestCode = READSDK)
    public void requestPhotoFail() {
        //失败之后的处理，我一般是跳到设置界面
        hasPermission = false;

        boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        boolean showCallPermission = ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.CALL_PHONE);
        if (showRequestPermission) {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        }

        if (showCallPermission) {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //TODO:先判断是否登录了，并且注册完成了
            case R.id.money:
                skipOtherActivity(WalletActivity.class, false);
                break;
            //拨打电话
            case R.id.customer:

                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    ToastMake.showToast(getResources().getString(R.string.string70));
                    hasReadPermission(Manifest.permission.CALL_PHONE);

                } else {
                    //TODO:权限申请成功
                    android.app.AlertDialog.Builder builder2 = new android.app.AlertDialog.Builder(MainActivity.this);
                    builder2.setMessage("拨打客服电话4000209777");
                    builder2.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder2.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            //需要后台提供
                            tellPhone("4000209777");
                            dialog.dismiss();
                        }
                    });
                    android.app.AlertDialog dialog = builder2.create();
                    dialog.show();
                }
                break;
            case R.id.setting:

                skipOtherActivity(SettingActivity.class, false);
                break;
            case R.id.fix:
                skipOtherActivity(EquipFixActivity.class, false);
                break;
            case R.id.user:
                //TODO:打开侧滑菜单
                mDrawer.openDrawer(GravityCompat.START);
                break;
            case R.id.message:
                startActivity(new Intent(MainActivity.this, EmailActivity.class));
                break;
            case R.id.share:
                showShare();
                break;
        }
    }

    private void showShare() {

        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // title标题，微信、QQ和QQ空间等平台使用
        oks.setTitle(getString(R.string.string31));
        // titleUrl QQ和QQ空间跳转链接
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url在微信、微博，Facebook等平台中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网使用
        oks.setComment("我是测试评论文本");
        // 启动分享GUI
        oks.show(this);

    }

    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return title[position];
        }

        @Override
        public Fragment getItem(int position) {


            return mFragments.get(position);
        }
    }

    //DrawerLayout不能全屏滑动的问题
    public void setDrawerLeftEdgeSize(Activity activity, DrawerLayout drawerLayout, float displayWidthPercentage) {
        if (activity == null || drawerLayout == null)
            return;
        try {
            // find ViewDragHelper and set it accessible
            Field leftDraggerField = drawerLayout.getClass().getDeclaredField("mLeftDragger");
            leftDraggerField.setAccessible(true);
            ViewDragHelper leftDragger = (ViewDragHelper) leftDraggerField.get(drawerLayout);
            Field edgeSizeField = leftDragger.getClass().getDeclaredField("mEdgeSize");
            edgeSizeField.setAccessible(true);
            int edgeSize = edgeSizeField.getInt(leftDragger);
            DisplayMetrics dm = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
            edgeSizeField.setInt(leftDragger, (int) (dm.widthPixels * displayWidthPercentage));
        } catch (Exception e) {
        }
    }

    private void UpdataApk() {

        int versionCode = getVersionCode();
        String versionNme = getVersionName();
        if (versionNme.contains(".")) {
            String[] vs_name = versionNme.split("\\.");

            for (int i = 0; i < vs_name.length; i++) {
                if (!vs_name[i].equals("")) {
                    if (i == 0) {
                        vs_name1 = Integer.valueOf(vs_name[0]);
                    }
                    if (i == 1) {
                        vs_name2 = Integer.valueOf(vs_name[1]);
                    }
                    if (i == 2) {
                        vs_name3 = Integer.valueOf(vs_name[2]);
                    }
                }
            }

        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils
                        .get()
                        .url(UriContect.VERSION)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {

                            }

                            @Override
                            public void onResponse(String response, int id) {
                                UpDataBeen dataBeen = GsonUtil.parseJsonToBean(response, UpDataBeen.class);
                                if (dataBeen == null) {
                                    return;
                                }
                                if (!TextUtils.equals(dataBeen.getStatus(), "1")) {

                                    return;
                                } else {
                                    String version = dataBeen.getVersion();
                                    final String url = dataBeen.getUrl();
                                    final String title = dataBeen.getTitle();
                                    final String msg = dataBeen.getMsg();
                                    if (version.contains(".")) {
                                        String[] sv_name = version.split("\\.");

                                        for (int i = 0; i < sv_name.length; i++) {

                                            if (!sv_name[i].equals("")) {
                                                if (i == 0) {
                                                    sv_name1 = Integer.valueOf(sv_name[0]);
                                                    System.out.println(sv_name1 + "");
                                                }
                                                if (i == 1) {
                                                    sv_name2 = Integer.valueOf(sv_name[1]);
                                                    System.out.println(sv_name2 + "");
                                                }
                                                if (i == 2) {
                                                    sv_name3 = Integer.valueOf(sv_name[2]);
                                                    System.out.println(sv_name3 + "");
                                                }
                                            }
                                        }
                                        if (vs_name1 > sv_name1) {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    showDialog(title, msg, url);
                                                }
                                            });
                                        } else {
                                            if (vs_name2 > sv_name2) {

                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        showDialog(title, msg, url);
                                                    }
                                                });

                                            } else {

                                                if (vs_name3 > sv_name3) {

                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            showDialog(title, msg, url);
                                                        }
                                                    });

                                                } else {

                                                    showNoUpadata("版本提示", "已经是最新版本了");
                                                }

                                            }
                                        }
                                    }
                                }
                            }
                        });
            }
        }).start();


    }

    private void showNoUpadata(String title, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(title);
        builder.setCancelable(false);
        builder.setMessage(message);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    /**
     * 获取软件版本号
     *
     * @return
     */
    private int getVersionCode() {
        int versionCode = 0;
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = MainActivity.this.getPackageManager().getPackageInfo(
                    getPackageName(), 0).versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionCode;
    }


    //TODO:进行版本升级操作

    /**
     * 获取版本名字
     *
     * @return
     */
    private String getVersionName() {
        String versionName = "";
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionName = MainActivity.this.getPackageManager().getPackageInfo(
                    getPackageName(), 0).versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

    //弹出对话框
    private void showDialog(String title, String message, final String url) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(title);
        builder.setCancelable(false);
        builder.setMessage(message);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                ToastMake.showToast("取消升级");
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                ToastMake.showToast("确定升级");

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //TODO:进行升级
                        downLoadApk(url);
                    }
                }).start();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void downLoadApk(String url) {
        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "chezai.apk") {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastMake.showToast(call.toString());
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        if (hasPermission) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                //判读版本是否在7.0以上
                                //新的启动方法
                                Uri apkUri = FileProvider.getUriForFile(MainActivity.this, getLocalClassName() + ".fileprovider", response);//在AndroidManifest中的android:authorities值
                                Intent install = new Intent(Intent.ACTION_VIEW);
                                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                                startActivity(install);
                            } else {
                                //以前的启动方法
                                // 通过Intent安装APK文件
                                Intent install = new Intent(Intent.ACTION_VIEW);
                                install.setDataAndType(Uri.fromFile(response.getAbsoluteFile()), "application/vnd.android.package-archive");
                                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(install);
                            }

                        } else {
                            ToastMake.showToast("请添加读取内存卡权限才能获得最新的版本");
                        }

                    }


                    @Override
                    public void inProgress(final float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                        myProgress = (int) progress;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //TODO:可以自定义进度条
                                //                                ProgressBar progressBar = new ProgressBar(MainActivity.this, null, android.R.attr.progressBarStyleHorizontal);
                                //                                progressBar.setMax(100);
                                //                                progressBar.setProgress(myProgress);

                            }
                        });


                    }
                });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (mDrawer.isDrawerOpen(GravityCompat.START)) {
                mDrawer.closeDrawer(GravityCompat.START);
                return true;
            }
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastMake.showToast(getResources().getString(R.string.string28));
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void tellPhone(String s) {
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            ToastMake.showToast("拨打电话需要授权拨打电话");

            boolean showCallPermission = ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.CALL_PHONE);
            if (showCallPermission) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivity(intent);
            }

        } else {
            Intent intent = new Intent(Intent.ACTION_CALL);
            Uri data = Uri.parse("tel:" + s);
            intent.setData(data);
            startActivity(intent);
        }
    }
}
